import json
import os
import re
import urllib.parse
from lxml import etree
from logger_config import logger


def extract_gender_position(html):
    # 初始化结果字典
    result = {'gender': '未知', 'position': '未知'}

    # 匹配角色信息
    position_pattern = r'<td\s+class="multi-row">角色</td>\s*<td>\s*([^<]+?)\s*</td>'
    position_match = re.search(position_pattern, html)
    if position_match:
        result['position'] = position_match.group(1).strip()

    # 匹配性别信息
    gender_pattern = r'<td\s+class="multi-row">性别</td>\s*<td>\s*([^<]+?)\s*</td>'
    gender_match = re.search(gender_pattern, html)
    if gender_match:
        result['gender'] = gender_match.group(1).strip()

    return result

async def save_cookie(cookie):
    """保存cookies到文件"""
    json_cookies = json.dumps(cookie, ensure_ascii=False)
    with open("cookie.txt", 'w', encoding="utf-8") as file:
        file.write(json_cookies)

async def load_cookie():
    """从文件加载cookies"""
    try:
        with open("cookie.txt", 'r', encoding="utf-8") as file:
            return json.load(file)
    except FileNotFoundError:
        logger.warning("Cookie file not found")
        return []
    except json.JSONDecodeError:
        logger.error("Invalid cookie file format")
        return []